<template>
  <div class="chat-container">
    <!-- 菜单栏 -->
    <div class="menu-bar">
      <div class="menu-left">
        <div class="project-select" v-if="!state.isvisitor">
          <label for="project-selector">Project</label>
          <select v-model="selectedProjectToken" id="project-selector" class="project-dropdown"
            @change="handleProjectChange">
            <option v-for="project in projects" :key="project.value" :value="project.value">
              {{ project.label }}
            </option>
          </select>
          <button @click="handleProjectChange" class="link-button">Link</button>
          <a-popover  :content="socket_namespace || ''" trigger="hover" color="#ccc">
            <div @click="copyNamespace" class="onCopy">
              Namespace
            </div>
          </a-popover>
        </div>
      </div>
      <div class="menu-right">
        <div class="route-select">
          <label for="route-selector">Msg Route</label>
          <select v-model="selectedRoute" id="route-selector" class="route-dropdown" @change="handleRouteChange">
            <option v-for="route in availableRoutes" :key="route.value" :value="route.value">
              {{ route.label }}
            </option>
          </select>
        </div>
        <div class="route-select">
          <label for="audio-route-selector">Audio Route</label>
          <select v-model="selectedAudioRoute" id="audio-route-selector" class="route-dropdown"
            @change="handleAudioRouteChange">
            <option v-for="route in availableAudioRoutes" :key="route.value" :value="route.value">
              {{ route.label }}
            </option>
          </select>
        </div>
        <div class="route-select">
          <label for="image-route-selector">Img Route</label>
          <select v-model="selectedImageRoute" id="image-route-selector" class="route-dropdown"
            @change="handleImageRouteChange">
            <option v-for="route in availableImageRoutes" :key="route.value" :value="route.value">
              {{ route.label }}
            </option>
          </select>
        </div>
      </div>
    </div>

    <!-- 对话记录区域 -->
    <div class="messages" ref="messagesContainerRef">
      <div v-for="message in messages" :key="message.id" class="message">
        <div v-if="message.type === 'text'" class="message-text">
          <NormalMessage :content="message.content" :sender="message.sender" :timestamp="message.timestamp" />
        </div>

        <FunctionTest v-else-if="message.type === 'functionTest'" :input="message.content"
          @response="handleFunctionResponse" class="function-test-message" />
      </div>
    </div>

    <!-- 输入框区域 -->
    <div class="input-container">
      <textarea v-model="message" class="message-input" placeholder="Type your message..."
        :style="{ height: inputHeight + 'px' }" @input="adjustInputHeight"
        @keydown.enter.prevent="handleEnter"></textarea>
      <div class="control">
        <a-popover content="record" placement="top" trigger="hover" color="#8ec7e1">
          <div class="icon1" @click="isRecording ? stopRecording() : startAudioRecording()"
            :class="{ btn_disabled: !selectedAudioRoute }">
            <Icon :Fill="isRecording ? '#FF0000' : '#000000'" :W="24" :H="24" name="record" />
          </div>
        </a-popover>
        <a-popover content="upload image" placement="top" trigger="hover" color="#8ec7e1">
          <div class="icon1" @click="uploadImageHandler" :class="{ btn_disabled: !selectedImageRoute }">
            <Icon name="file" :W="24" :H="24" />
          </div>
        </a-popover>
        <a-popover content="send message" placement="top" trigger="hover" color="#8ec7e1">
          <div class="icon1" @click="sendMessageHandler" :class="{ btn_disabled: isSending }">
            <Icon name="send" :W="24" :H="24" />
          </div>
        </a-popover>
      </div>


      <!-- <button @click="sendMessageHandler" class="send-button">Send</button> -->
    </div>

    <!-- <div class="audio-controls" v-if="selectedAudioRoute">
      <button 
        @click="isRecording ? stopRecording() : startAudioRecording()"
        :class="{ 'recording': isRecording }"
      >
        {{ isRecording ? 'Stop Recording' : 'Start Recording' }}
      </button>
      <span v-if="isRecording" class="recording-indicator">● Recording...</span>
    </div> -->

    <!-- <div class="image-controls" v-if="selectedImageRoute">
      <button @click="uploadImageHandler">Upload Image</button>
    </div> -->
  </div>
</template>

<script lang="ts">
export default {
  name: 'ChatView',
}
</script>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue';
import { message as antdMessage} from 'ant-design-vue';
import {useServer} from '@/components/ts/useServer';
import {useUserStore} from '@/stores/userStore';
import FunctionTest from '@/components/chatComponents/FunctionTest.vue'
import NormalMessage from '@/components/chatComponents/NormalMessage.vue'
import Icon from '../components/icons/Icon.vue'
const message = ref('');
const inputHeight = ref(20);
const projects = ref<{ value: string; label: string; id: string }[]>([]);
const selectedProjectToken = ref<string>('');
const selectedRoute = ref<string>('');
const selectedAudioRoute = ref<string>('');
const selectedImageRoute = ref<string>('');
const availableRoutes = ref<{ value: string; label: string }[]>([]);
const availableAudioRoutes = ref<{ value: string; label: string }[]>([]);
const availableImageRoutes = ref<{ value: string; label: string }[]>([]);
const state = useUserStore()
//ai正在生成消息的标志位
const isSending = ref(false);
const { 
  post, 
  ws, 
  connectWebSocket, 
  sendMessage, 
  closeWebSocket, 
  messages, 
  isConnected, 
  currentProjectToken, 
  sendDataInRoute,
  selectMessageRoute,
  selectAudioRoute,
  startAudioRecording,
  stopAudioRecording,
  isRecording,
  selectImageRoute,
  messageRoute
} = useServer();
const props = withDefaults(
  defineProps<{
    projectID:string
  }>(),
  {
    projectID:''
  }
)
const socket_namespace=ref('')
// 使用后端接口获取 project 列表
const getProjects = async () => {
  try {
    const response = await post('getUserRunningProjects', { userID: state.currentUser });
    projects.value = response.data.map((project: any) => ({
      value: project.full_url,
      label: `${project.username}_${project.project_name}`,
      id:project.project_id
    }));
    if(state.isvisitor){
      selectedProjectToken.value = projects.value.find((project) => project.id === props.projectID)?.value || ''
      await handleProjectChange()
    }
  } catch (error) {
    console.error('Failed to fetch projects:', error);
  }
};

// 获取可用路由
const getAvailableRoutes = async () => {
  try {
    const response = await post('getAvailableRoutes', { project_token: selectedProjectToken.value });
    console.log(response)
    if(!response.success){
      console.log('获取可用路由失败')
      return
    }
    availableRoutes.value = response.data.messageRoutes.map((route: any) => ({
      value: route.value,
      label: route.node_name
    }));
    availableAudioRoutes.value = response.data.audioRoutes.map((route: any) => ({
      value: route.value,
      label: route.node_name
    }));
    availableImageRoutes.value = response.data.imageRoutes.map((route: any) => ({
      value: route.value,
      label: route.node_name
    }));
  } catch (error) {
    console.error('Failed to fetch routes:', error);
  }
};

// 监听 project 变化，切换 WebSocket 连接
const handleProjectChange = async () => {
  if(!state.isvisitor)
  console.log('Selected project changed:', selectedProjectToken.value)
  
  // 关闭当前项目的连接
  if (currentProjectToken.value) {
    closeWebSocket(currentProjectToken.value);
  }

  if (selectedProjectToken.value) {
    connectWebSocket(selectedProjectToken.value);
    socket_namespace.value = selectedProjectToken.value
    // 获取新的可用路由
    await getAvailableRoutes();
  }
};

// 处理消息路由变化
const handleRouteChange = () => {
  console.log('Selected message route changed:', selectedRoute.value);
  // 这里可以添加路由切换的相关逻辑
  if(selectedRoute.value){
    selectMessageRoute(selectedRoute.value);
  }
};

// 处理音频路由变化
const handleAudioRouteChange = () => {
  console.log('Selected audio route changed:', selectedAudioRoute.value);
  if(selectedAudioRoute.value){
    selectAudioRoute(selectedAudioRoute.value);
  }
};

// 处理图片路由变化
const handleImageRouteChange = () => {
  console.log('Selected image route changed:', selectedImageRoute.value);
  if(selectedImageRoute.value){
    selectImageRoute(selectedImageRoute.value);
  }
};

// 停止音频录制
const stopRecording = () => {
  stopAudioRecording();
};

// 发送消息
const sendMessageHandler = () => {
  if (message.value.trim() === '') return;
  if(!messageRoute?.value){
    antdMessage.info('You did not select a message route')
    return
  }
  // Add user message to messages array
  messages.value.push({
    id: Date.now().toString(),
    content: {data:{'text':message.value, 'end':true}},
    sender: 'user',
    type: 'text',
    timestamp: Date.now()
  });
  
  sendMessage({'type':'text', 'data':message.value});

  message.value = '';
};
let messagesContainerRef = ref<HTMLDivElement>(null);
watch(
  messages,(newMessages) => {
    if (newMessages.length === 0) return;

    nextTick(() => {
      const el = messagesContainerRef.value;
      if (el) {
        el.scrollTop = el.scrollHeight;
      }
    });
  },
  { deep: true } // 消息数组内部元素改变也会触发
);
const handleFunctionResponse = (response: any) => {
  console.log('Function response:', response)
  
  const messageToSend = {
    type: 'function_response',
    route: response.route,
    correlation_id: response.correlation_id,
    status: response.status,
    data: response.result
  }

  const currentWs = ws();
  if (currentWs && currentWs.connected) {
    sendDataInRoute(response.route, messageToSend);
  } else {
    console.error('WebSocket is not connected')
  }
}

// 上传图片处理函数
const uploadImageHandler = () => {
  // 创建一个隐藏的文件输入元素
  const input = document.createElement('input'); // 创建input元素
  input.type = 'file'; // 设置类型为文件
  input.accept = 'image/*'; // 只接受图片类型
  input.style.display = 'none'; // 隐藏input

  // 监听文件选择事件
  input.onchange = (event: Event) => {
    const target = event.target as HTMLInputElement; // 获取事件目标
    if (target.files && target.files.length > 0) { // 判断是否有文件被选择
      const file = target.files[0]; // 获取第一个文件
      // 这里可以添加上传图片到服务器的逻辑
      // base64 encode the image
      const reader = new FileReader();
      reader.onload = (e) => {
        const base64Image = e.target?.result as string;
        console.log('Base64 image:',  {'type':'image', 'data':base64Image})
        sendDataInRoute(selectedImageRoute.value, {'type':'image', 'data':base64Image})
      }
      reader.readAsDataURL(file as Blob);
    }
  };

  document.body.appendChild(input); // 将input添加到body中
  input.click(); // 触发点击，打开文件选择器
  document.body.removeChild(input); // 移除input元素
}

// 在组件挂载后获取 project
onMounted(() => {
    getProjects();
});

onUnmounted(() => {
  stopRecording();
  if (currentProjectToken.value) {
    closeWebSocket(currentProjectToken.value);
  }
});

// 调整输入框高度
const adjustInputHeight = () => {
  const textarea = document.querySelector('.message-input') as HTMLTextAreaElement;
  textarea.style.height = 'auto'
  textarea.style.height = textarea.scrollHeight + 'px'
  if (textarea) {
    inputHeight.value = textarea.scrollHeight > 20 ? textarea.scrollHeight : 20;
  }
};

// 处理Enter键发送消息
const handleEnter = (event: KeyboardEvent) => {
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault();//阻止事件默认行为
    sendMessageHandler();
  }
};

const copyNamespace = () => {
  if (socket_namespace.value) {
    navigator.clipboard.writeText(socket_namespace.value);
    antdMessage.success('Namespace copied to clipboard');
  }
}
</script>

<style scoped lang="scss">
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  padding: 20px;
  background-color: #f5f5f5;
  gap: 20px;
}

.menu-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background-color: #ffffff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  font-size: 14px;
  font-family:'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.menu-left, .menu-right {
  display: flex;
  align-items: center;
  gap: 8px;
}

.project-select, .route-select {
  display: flex;
  align-items: center;
  gap: 10px;
}

.project-select label, .route-select label {
  font-size: 14px;
  color: #333;
  font-weight: 500;
  white-space: nowrap;
}

.project-dropdown, .route-dropdown {
  padding: 8px 12px;
  border-radius: 8px;
  border: 1px solid #ddd;
  font-size: 14px;
  min-width: 180px;
  background-color: #fff;
  cursor: pointer;
}

.project-dropdown{
  min-width: 180px;
}
.route-dropdown{
  min-width: 140px;
}

.link-button {
  padding: 8px 16px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s ease;
  margin-right: 10px;
}

.link-button:hover {
  background-color: #0056b3;
}

.messages {
  flex-grow: 1;
  overflow-y: auto;
  padding: 20px;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  color: #fff; /* 文字白色更清晰 */
  &::-webkit-scrollbar {
    width: 8px;
    height: 8px;
  }

&::-webkit-scrollbar-thumb {
  background-color: #4a90e2;
  border-radius: 6px;
  transition: background-color 0.3s ease;
}

&::-webkit-scrollbar-thumb:hover {
  background-color: #1e6fd9;
}

  &::-webkit-scrollbar-track {
    background: transparent;
    border-radius: 6px;
  }
}

.message {
  margin-bottom: 15px;
}

.message-text {
  width: 100%;
}

.function-test-message {
  margin-top: 10px;
}

.input-container {
  padding: 15px;
 
  background-color: #ffffff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  
  textarea{
    display:flex;
    align-content: center;
    width:100%;
    max-height: 150px;
    font-size: 14px;
  }
  .control{
    display: flex;
    gap: 10px;
    align-items: center;
    align-content: center;
    justify-content: flex-end;
  }
    .icon1 {
      border: none;
      border-radius: 100%;
      transition: transform 0.2s ease, background 0.2s ease; // 👈 平滑动画过渡
  
      &:hover {
        transform: scale(1.1);
        background: rgba(214, 223, 225, 0.412);
        cursor: pointer;
      }
    }
          .btn_disabled {
        opacity: 0.5;
        /* 变淡 */
        pointer-events: none;
        /* 不可点击 */
        cursor: not-allowed;
        /* 鼠标指针变叉 */
        transform: none !important;
        /* 禁用动画 */
        background: transparent !important;
      }
}

.message-input {
  flex-grow: 1;
  min-height: 40px;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 8px;
  resize: none;
  font-size: 14px;
  line-height: 1.5;
}

.message-input:focus {
  outline: none;
  border-color: #007bff;
}

.send-button {
  padding: 12px 24px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.send-button:hover {
  background-color: #0056b3;
  transform: translateY(-1px);
}

.send-button:active {
  transform: translateY(0);
}

.audio-controls {
  margin: 10px 0;
  display: flex;
  align-items: center;
  gap: 10px;
}

.recording {
  background-color: #ff4444;
  color: white;
}

.recording-indicator {
  color: #ff4444;
  animation: pulse 1s infinite;
}

@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.5; }
  100% { opacity: 1; }
}

.onCopy{
  cursor: pointer;
  color:#5da1ea;
  font-family:'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
  font-size:16px;
  &:hover{
    color: #007bff;
    text-decoration: underline;
  }
}
</style>
